package com.shanghaionstar.nav;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.sqlite.entities.PoiSearchHistory;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.weight.CustomImageView;
import com.onstar.cn.weight.DeleteEditText;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.iview.ILoginListener;
import com.shanghaionstar.nav.adapter.NavPoiSearchHistoryNoTbtAdapter;
import com.shanghaionstar.nav.adapter.NavPoiSearchListAdapter;
import com.shanghaionstar.nav.iview.INavSetAddressView;
import com.shanghaionstar.nav.model.MapChoosePoiType;
import com.shanghaionstar.nav.presenter.NavSetAddressPresenter;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.nav.util.FindMyLocate;
import com.shanghaionstar.sqlite.SearchHistoryImpl;
import com.shanghaionstar.sqlite.UserAddressInfoImpl;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.LoginUtil;
import com.shanghaionstar.utils.MapHandler;
import com.shanghaionstar.utils.NavHolder;

import java.util.List;

/**
 * Created by 6335yz on 2016/7/18.
 */
public class NavSetAddressFragment extends BaseFragment implements INavSetAddressView, ILoginListener {
    @FindViewById(R.id.frame_back)
    private RelativeLayout frame_back;
    @FindViewById(R.id.edit_search_addressinfo)
    private DeleteEditText edit_search_addressinfo;
    @FindViewById(R.id.right_btn)
    private CustomImageView right_btn;

    //地图选点
    @FindViewById(R.id.btn_map_choos_point)
    private Button btn_map_choos_point;
    //收藏夹
    @FindViewById(R.id.btn_favorites)
    private Button btn_favorites;
    //显示搜索历史记录列表
    @FindViewById(R.id.listview_search_history)
    private ListView listview_search_history;
    //显示搜索结果信息列表
    @FindViewById(R.id.poilist_view)
    private ListView poilist_view;
    //清空历史记录
    @FindViewById(R.id.btn_clean_history_record)
    private Button btn_clean_history_record;
    @FindViewById(R.id.no_list_data)
    private TextView no_list_data;

    private String flag;//用来标记是设置家或是公司的地址
    private int pagertype;//标记跳转的页面
    private int startorendlocation;//标记路线规划的起始和终点位置

    public static final int SEARCHMAIN = 0;
    public static final int ROUTEPLAN = 1;

    public static final int STARTLOCATION = 2;
    public static final int ENDLOCATION = 3;

    private boolean isNextPage = false;
    private int lastItemIndex = 0;
    private List<PoiItemInfo> searchPoiList;

    //搜索历史
    private List<PoiSearchHistory> searchHistoryList;
    private NavPoiSearchHistoryNoTbtAdapter poiSearchHistroyListAdapter;
    private SearchHistoryImpl impl;
    //家或公司的地址信息
    private PoiItemInfo homeOrCompanyPoiItemInfo = new PoiItemInfo();
    private UserAddressInfoImpl userAddressInfoImpl;
    private NavPoiSearchListAdapter navPoiSearchListAdapter;
    private AbstractMapActivity mapActivity;
    private MapHandler mapHandler;
    private FragmentManager fragmentManager;
    private NavSetAddressPresenter navSetAddressPresenter;

    private List<PoiSearchHistory> mSearchHistoryList;
    private MapChoosePoiType mapChoosePoiType;

    ProgressDialog progDialog;
    private FindMyLocate findMyLocate;

    @Override
    public int getLayoutId() {
        return R.layout.nav_setting_address;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        navSetAddressPresenter = new NavSetAddressPresenter(mapActivity.getScheduler(), mapActivity, mapHandler);
        if (CommonUtil.isNull(NavHolder.getInstance(mapActivity).getCurrentCity())) {
            requestRunTimePermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new PermissionCall() {
                @Override
                public void requestSuccess() {
                    findMyLocate = new FindMyLocate(mapActivity, mapHandler);
                    findMyLocate.beginLocate();
                }

                @Override
                public void refused() {

                }
            });
        }
        navSetAddressPresenter.setView(this);
        navSetAddressPresenter.getSearchHistroy();
        progDialog = new ProgressDialog(mapActivity);
        initEditText();
        if (getArguments().getSerializable("mapChoosePoiType") != null) {
            mapChoosePoiType = (MapChoosePoiType) getArguments().getSerializable("mapChoosePoiType");
        }
        frame_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Homesetting_return.getStringValue());
                hideSoftInput();
                goBack();
            }
        });
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mapActivity = (AbstractMapActivity) activity;
        fragmentManager = mapActivity.getSupportFragmentManager();
        mapHandler = mapActivity.getChooseMapHandler();
    }

    @Override
    public void showCleanBtnOrNot(boolean isShow) {
        if (isShow) {
            btn_clean_history_record.setVisibility(View.VISIBLE);
            no_list_data.setVisibility(View.GONE);
        } else {
            btn_clean_history_record.setVisibility(View.GONE);
            no_list_data.setVisibility(View.VISIBLE);
            no_list_data.setText(getResources().getString(R.string.nav_no_search_poi_data));
        }
    }

    @Override
    public void showSearchHistory(final List<PoiSearchHistory> searchHistoryList) {
        if (poiSearchHistroyListAdapter == null) {
            mSearchHistoryList = searchHistoryList;
            poiSearchHistroyListAdapter = new NavPoiSearchHistoryNoTbtAdapter(mSearchHistoryList, mapActivity, navSetAddressPresenter);
            listview_search_history.setAdapter(poiSearchHistroyListAdapter);
            listview_search_history.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    PoiSearchHistory poiSearchHistory = searchHistoryList.get(position);
                    PoiItemInfo poiItemInfo = new PoiItemInfo();
                    poiItemInfo.setTitle(poiSearchHistory.getName());
                    poiItemInfo.setThreadId(poiSearchHistory.getSearchtime());
                    poiItemInfo.setAddress(poiSearchHistory.getAddress());
                    poiItemInfo.setLatitude(poiSearchHistory.getLat());
                    poiItemInfo.setLongitude(poiSearchHistory.getLon());
                    poiItemInfo.setCityName(poiSearchHistory.getCityname());
                    poiItemInfo.setTelphone(poiSearchHistory.getPhone());
//                    homeOrCompanyPoiItemInfo = poiItemInfo;
                    navSetAddressPresenter.submit(poiItemInfo, mapChoosePoiType);
                }
            });
        } else {
            poiSearchHistroyListAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 搜索结果回调
     *
     * @param searchPoiList
     */
    @Override
    public void showSearchResult(final List<PoiItemInfo> searchPoiList) {
        poilist_view.setVisibility(View.VISIBLE);
        isNextPage = mapHandler.IfhasNextPage();
        if (navPoiSearchListAdapter == null) {
            navPoiSearchListAdapter = new NavPoiSearchListAdapter(searchPoiList, mapActivity, false, -1);
            poilist_view.setAdapter(navPoiSearchListAdapter);
            poilist_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    mapActivity.hideSoftInput();
                    navSetAddressPresenter.submit(searchPoiList.get(position), mapChoosePoiType);
                }
            });
            poilist_view.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    lastItemIndex = firstVisibleItem + visibleItemCount;
                }

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    if (!isNextPage) {
                        return;
                    }
                    if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
                            && lastItemIndex == navPoiSearchListAdapter.getCount()) {
                        try {
                            mapHandler.nextPageResult();
                            isNextPage = false;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        } else {
            navPoiSearchListAdapter.setmItemList(searchPoiList);
            navPoiSearchListAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void showSearchResultWithNodata() {

    }

    @Override
    public void switchToPrevious(PoiItemInfo poiItemInfo) {

    }

    @Override
    public void setLoading(boolean isLoading) {

    }

    @Override
    public void onResponseError(OnStarException e) {

    }

    @Override
    public void onReponseSuccess(Object object) {
        NavChoosePointInMapFragment navChoosePointInMapFragment = (NavChoosePointInMapFragment) fragmentManager.findFragmentByTag(NavChoosePointInMapFragment.class.getSimpleName());
        mapActivity.removeUntilFragment(fragmentManager, navChoosePointInMapFragment.getPreFragment(), false);
    }

    @Override
    public Activity onActivity() {
        return null;
    }

    @Override
    public void showMapLoading(boolean isShow, String msg) {
        if (progDialog != null) {
            if (isShow) {
                if (!progDialog.isShowing()) {
                    progDialog.setTitle(getString(R.string.waiting));
                    progDialog.setMessage(msg);
                    progDialog.show();
                }
            } else {
                if (progDialog.isShowing()) {
                    progDialog.dismiss();
                }
            }
        }
    }

    @OnClick({R.id.right_btn, R.id.btn_favorites, R.id.btn_map_choos_point, R.id.btn_clean_history_record})
    public void onClick(View view) {
        hideSoftInput();
        switch (view.getId()) {
            case R.id.btn_clean_history_record:
                BusinessUtil.sendReportByClickType(baseActivity, FunctionNameFindId.Homesetting_clearhistory.getStringValue());
                navSetAddressPresenter.clearHistory();
                break;
            case R.id.right_btn:
                BusinessUtil.sendReportByClickType(baseActivity, FunctionNameFindId.Homesetting_clicksearchhistory.getStringValue());
                navSetAddressPresenter.search(String.valueOf(edit_search_addressinfo.getText()));
                break;
            case R.id.btn_favorites:
                BusinessUtil.sendReportByClickType(baseActivity, FunctionNameFindId.Homesetting_clickfavorite.getStringValue());
                new LoginUtil().loginAndActionCallBack(baseActivity, RxConstants.NAV_SET_ADDRESS, this, null);
                break;
            case R.id.btn_map_choos_point:
                BusinessUtil.sendReportByClickType(baseActivity, FunctionNameFindId.Homesetting_clickpickpointfrommap.getStringValue());
                mapActivity.showFragment(fragmentManager, NavChoosePointInMapFragment.class, getClass());
                break;
        }
    }

    private void initEditText() {
        edit_search_addressinfo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    navSetAddressPresenter.search(String.valueOf(edit_search_addressinfo.getText()));
                    return true;
                }
                return false;
            }
        });
        edit_search_addressinfo.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Homesetting_clicksearchfield.getStringValue());
                }
            }
        });
        edit_search_addressinfo.setOnTextChangeListener(new DeleteEditText.OnTextChangeListener() {
            @Override
            public void textChangeListener(View view, CharSequence text) {
                if (CommonUtil.isNull(text.toString())) {
                    right_btn.setVisibility(View.GONE);
                } else {
                    right_btn.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (CommonUtil.isNull(edit_search_addressinfo.getText().toString().trim())) {
                    listview_search_history.setVisibility(View.GONE);
                    edit_search_addressinfo.clearFocus();
                }
            }
        });
    }

    public static NavSetAddressFragment newInstance(MapChoosePoiType mapChoosePoiType) {
        Bundle bundle = new Bundle();
        NavSetAddressFragment navSetAddressFragment = new NavSetAddressFragment();
        bundle.putSerializable("mapChoosePoiType", mapChoosePoiType);
        navSetAddressFragment.setArguments(bundle);
        return navSetAddressFragment;
    }

    @Override
    public void onLogin(Bundle bundle, String resultCode) {
        mapActivity.addFragment(fragmentManager, NavFavListSimpleListSimpleFragment.newInstance(mapChoosePoiType), true);
        mapActivity.showFragment(fragmentManager, NavFavListSimpleListSimpleFragment.class, getClass());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (findMyLocate != null) {
            findMyLocate.clear();
        }
    }
}
